//app.js
App({
  host: 'https://sudongzaixian.com/',
  // host: 'http://www.sdzx.com/',
  data: {

  },

  onLaunch: function () {
    var that = this;
    //检查登录状态
    wx.checkSession({
      success: function () {
        //session 未过期，并且在本生命周期一直有效
        // that.globalData.is_login = true;
        // that.platfromLogin();
      },
      fail: function () {
        //登录态过期 重新调用微信登录
        try {
          wx.removeStorageSync('Cookie-PHPSESSID');
          that.wxLogin();
        } catch (e) {
          // Do something when catch error
        }
      }
    })

    this.getUserInfo(function (re) {
      that.globalData.userInfo = re;
    });
  },
  ball_animate: function (e,that) {
    var animation = this.animation
    var balls = that.data.balls
    var endY = 555
    for (let i = 0; i <= balls.length; i++) {
      let ball = balls[i]
      if (!ball.isShow) {
        //重置动画
        for (let j = 0 && j != i; j < balls.length; j++) {
          balls[j].isShow = false
          balls[j].style = ''
        }
        //执行动画
        ball.isShow = true
        ball.style = 'transition:transform 500ms linear 0ms, left, top;transform-origin:50% 50% 0px;'
          + 'left:' + (e.touches[0].clientX - 80) +
          'px;' + 'top:' + e.touches[0].clientY +
          'px;transform:translateY(555px);'
        break;
      }
    }
    that.setData({
      balls: balls
    })
  },
  set_stor: function (value) {
    if (value) {
      wx.getStorage({
        key: 'search_history',
        complete: function (res) {
          var data = res.data
          if (data) {
            for (let i in data.list) {
              if (data.list[i] == value) {
                return false
              }
            }
            data.list.push(value)
          } else {
            data = {}
            data.list = []
            data.list.push(value)
          }
          wx.setStorage({
            key: 'search_history',
            data: data,
          })
        },
      })
    }
  },
  cart_num: function (the) {
    var that = this;
    this.ajax({
      url: that.host + "mall/cart",
      success: function (res) {
        var data = res.data.data
        var cart_num = 0
        for (var i in data) {
          cart_num += parseInt(data[i].num)
        }
        that.globalData.cart_num = cart_num
        the.setData({
          cart_num: cart_num
        })
        return cart_num;
      }
    })
  },
  new_order:function(the){
    var that = this
    this.ajax({
      url: that.host + "mall/order/neworder",
      success: function (res) {
        var order_num = res.data.data.num
        that.globalData.order_num = order_num
        the.setData({
          order_num: order_num
        })
        return order_num;
      }
    })
  },

  wxLogin: function (auto) {
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          that.ajax({
            url: that.host + 'mall/Login/wxLogin',
            data: {
              code: res.code
            },
            success: function (d) {
              if (auto == true) {
                that.platfromLogin();
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },

  platfromLogin: function () {
    setTimeout(function () {
      wx.navigateTo({
        url: '/pages/usercenter/login/login'
      })
    }, 500);
  },

  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.getUserInfo({
        withCredentials: false,
        success: function (res) {
          that.globalData.userInfo = res.userInfo
          typeof cb == "function" && cb(that.globalData.userInfo)
        }
      })
    }
  },


  /**
   * 带数组的setData
   **/
  arrset: function (o) {
    var obj = {}
    if (o.checkObj) {
      obj[o.str] = false
    } else {
      obj[o.str] = true
    }
    o.that.setData(obj)
    return obj
  },
  globalData: {
    is_login: false,
    login_num: 0,
    userInfo: null,
    cart_num: 0,
    order_num:0,
    tabBar: [
      {
        pagePath: "/pages/index/index",
        text: "首页",
        img: "/statics/img/index.png",
        slectimg: "/statics/img/index-active.png",
        current: 0
      },
      {
        pagePath: "/pages/all_shop_list/all_shop_list",
        text: "全部商品",
        img: "/statics/img/all.png",
        slectimg: "/statics/img/all-active.png",
        current: 1
      },
      {
        pagePath: "/pages/used_list/used_list",
        text: "常用清单",
        img: "/statics/img/hot-list.png",
        slectimg: "/statics/img/hot-list-active.png",
        current: 2
      },
      {
        pagePath: "/pages/shop_cart/shop_cart",
        text: "购物车",
        img: "/statics/img/cart.png",
        slectimg: "/statics/img/cart-active.png",
        current: 3,
        nored: true
      },
      {
        pagePath: "/pages/usercenter/usercenter",
        text: "我的",
        img: "/statics/img/me.png",
        slectimg: "/statics/img/me-active.png",
        current: 4
      },
    ]
  },

  showTopTips: function (info, that) {
    that.setData({
      showTopTips: true,
      info: info
    });
    setTimeout(function () {
      that.setData({
        showTopTips: false,
        info: 'error'
      });
    }, 1500);
  },

  ajax: function (opt) {
    var that = this;
    var url = opt['url'],
      data = opt['data'],
      header = opt['header'] ? opt['header'] : {},
      method = opt['method'] ? opt['method'] : 'GET',
      dataType = opt['dataType'] ? opt['dataType'] : 'json',
      _success = opt['success'] ? opt['success'] : '',
      _fail = opt['fail'] ? opt['fail'] : '',
      _complete = opt['complete'] ? opt['complete'] : '';
    var _getCookie = function () {
      try {
        var res = wx.getStorageInfoSync(), _header = [], cookie_str = '';
        for (var i = 0; i < res.keys.length; i++) {
          if (new RegExp('Cookie-').test(res.keys[i])) {
            try {
              var value = wx.getStorageSync(res.keys[i]), cookie_name = res.keys[i].substring(7);
              if (value.hasOwnProperty('expires')) {
                var time = new Date().toGMTString(), date = new Date(value['expires']).toGMTString();
                if (time > date) {
                  continue;
                }
              }
              _header.push(cookie_name + '=' + value[cookie_name]);
            } catch (e) {
              console.log('get cookie ' + cookie_name + ' error');
            }
          }
        }
        if (_header.length > 0) {
          cookie_str = _header.join('; ');
        }
        return cookie_str;
      } catch (e) {
        console.log('_getCookie getStorageInfoSync  error');
      }
    }
    var cookieStr = _getCookie();
    if (cookieStr != '') { header['Cookie'] = cookieStr; }
    wx.request({
      url: url,
      method: method,
      dataType: dataType,
      data: data,
      header: header,
      success: function (res) {
        if (typeof _success == 'function') {
          _success(res);
        }
        if (res.data.data == 'login' && res.data.code <= 0) {
          // 调用平台登录  首次进app 自动登录，之后就不自动登录
          console.log('login_num=' + that.globalData.login_num);
          if (that.globalData.login_num == 0) {
            that.platfromLogin();
          } else {
            wx.showModal({
              title: '提示',
              content: '请先登录',
              success: function (res) {
                if (res.confirm) {
                  that.platfromLogin();
                } else if (res.cancel) {
                }
              }
            })
            return;
          }
        } else {
          that.globalData.is_login = true
        }
      },
      fail: function (res) {
        if (typeof _fail == 'function') {
          _fail(res);
        }
      },
      complete: function (res) {
        var header = res.header;
        if (header.hasOwnProperty('Set-Cookie')) {
          var str = header['Set-Cookie'];
          var cookieArr = {};
          var arr = str.split(/; path=\/,/);
          for (var i = 0; i < arr.length; i++) {
            var tmp1 = arr[i].split('; '), tmp2 = {}, cookie_name = '';
            for (var ii = 0; ii < tmp1.length; ii++) {
              var tmp3 = tmp1[ii].split('=');
              if (ii == 0) { cookie_name = tmp3[0]; }
              if (tmp3[0] != '' && tmp3[1] != '') { tmp2[tmp3[0]] = tmp3[1]; }
            }
            if (cookie_name != '') { cookieArr[cookie_name] = tmp2; }
          }
          for (var p in cookieArr) {
            switch (cookieArr[p][p]) {
              case 'deleted': {
                try {
                  wx.removeStorageSync('Cookie-' + p);
                } catch (e) {
                  wx.clearStorage();
                }
                break;
              }
              default: {
                try {
                  wx.setStorageSync('Cookie-' + p, cookieArr[p]);
                } catch (e) {
                  console.log('save cookie error');
                }
                break;
              }
            }
          }
        }
        if (typeof _complete == 'function') {
          _complete(res);
        }
      },
    })
  },
  add_cart: function (e, the, suc) {
    var goods_id = e.currentTarget.dataset.goods_id
    var specval_id = e.currentTarget.dataset.specval_id
    var that = this
    this.ajax({
      url: this.host + "mall/cart/edit",
      data: {
        goods_id: goods_id,
        specval_id: specval_id
      },
      success: function (re) {
        if (re.data.code > 0) {
          that.globalData.cart_num++
          the.setData({
            cart_num: that.globalData.cart_num
          })
        }
        if (suc) {
          suc(specval_id);
        }
      }
    })
  },
  //加法函数
  accAdd: function (arg1, arg2) {
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    return (arg1 * m + arg2 * m) / m
  },
  //减法函数
  Subtr: function (arg1, arg2) {
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
  },
  //乘法函数
  accMul: function (arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  },
  //除法函数
  // accDiv:function(arg1, arg2) {
  //   var t1 = 0, t2 = 0, r1, r2;
  //   try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
  //               try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
  //               with (Math) {
  //     r1 = Number(arg1.toString().replace(".", ""))
  //     r2 = Number(arg2.toString().replace(".", ""))
  //     return (r1 / r2) * pow(10, t2 - t1);
  //   }
  // },
  all_price: function (the) {
    var that = this
    this.ajax({
      url: that.host + "mall/cart",
      success: function (msg) {
        var data = msg.data.data
        var allprice = 0
        for (var i in data) {
          data[i].checked = true
          data[i].value = i
          allprice = that.accAdd(allprice, that.accMul(parseFloat(data[i].price), parseFloat(data[i].num))).toFixed(2)
        }
        the.setData({
          allprice: allprice
        })
      }
    })
  }
})
